// gesture-render.js
let canvas, ctx
let canvasSize = 300
let radius = 25
let padding = 30
let points = []
let selectedPoints = []
let currentTouch = null

// 初始化点位
const initPoints = () => {
  const gap = (canvasSize - 2 * padding - 3 * 2 * radius) / 2
  points = []
  for (let row = 0; row < 3; row++) {
    for (let col = 0; col < 3; col++) {
      const x = padding + radius + col * (gap + 2 * radius)
      const y = padding + radius + row * (gap + 2 * radius)
      points.push({ x, y, selected: false })
    }
  }
}

// 检测触摸点
const detectPoint = (touchX, touchY) => {
  for (let i = 0; i < points.length; i++) {
    const point = points[i]
    const dx = touchX - point.x
    const dy = touchY - point.y
    if (!point.selected && Math.sqrt(dx * dx + dy * dy) <= radius) {
      point.selected = true
      selectedPoints.push(i)
      break
    }
  }
}

// 绘制九宫格
const drawGrid = () => {
  ctx.clearRect(0, 0, canvasSize, canvasSize)
  points.forEach((point) => {
    ctx.beginPath()
    ctx.arc(point.x, point.y, radius, 0, 2 * Math.PI)
    ctx.strokeStyle = point.selected ? '#627eed' : '#ccc'
    ctx.lineWidth = 2
    ctx.stroke()
    ctx.closePath()

    if (point.selected) {
      ctx.beginPath()
      ctx.arc(point.x, point.y, radius / 2, 0, 2 * Math.PI)
      ctx.fillStyle = '#627eed'
      ctx.fill()
      ctx.closePath()
    }
  })

  if (selectedPoints.length > 0) {
    ctx.beginPath()
    ctx.strokeStyle = '#627eed'
    ctx.lineWidth = 3
    selectedPoints.forEach((index, idx) => {
      const point = points[index]
      if (idx === 0) {
        ctx.moveTo(point.x, point.y)
      } else {
        ctx.lineTo(point.x, point.y)
      }
    })
    if (currentTouch) {
      ctx.lineTo(currentTouch.x, currentTouch.y)
    }
    ctx.stroke()
    ctx.closePath()
  }
}

// 初始化
renderjs.onMessage((e) => {
  const { type, data } = e

  switch (type) {
    case 'init':
      canvas = e.canvas
      ctx = canvas.getContext('2d')
      canvasSize = data.canvasSize
      radius = data.radius
      padding = data.padding
      initPoints()
      drawGrid()
      break

    case 'touchStart':
    case 'touchMove':
      detectPoint(data.x, data.y)
      currentTouch = { x: data.x, y: data.y }
      drawGrid()
      break

    case 'touchEnd':
      console.log('手势密码序列:', selectedPoints)
      currentTouch = null
      setTimeout(() => {
        points.forEach((point) => (point.selected = false))
        selectedPoints = []
        drawGrid()
      }, 1000)
      break
  }
})
